import xml.etree.ElementTree as xml
import network


class BBApi:
    def __init__(self, login, password):
        self.login = login
        self.password = password
        self.loggedIn = False
        self.network = network.Network()

        p = {'login': self.login, 'code': self.password}
        data = self.network.first_get('http://bbapi.buzzerbeater.com/login.aspx', p)

        root = xml.fromstring(data)
        if root.tag == 'bbapi':
            if root.attrib['version'] != '1':
                print('Error: Invalid BBApi Version!')

        for child in root:
            if child.tag == 'loggedIn':
                self.loggedIn = True
            elif child.tag == 'error':
                print('Error:', child.attrib['message'])

    def logout(self):
        data = self.network.get('http://bbapi.buzzerbeater.com/logout.aspx')

        root = xml.fromstring(data)
        for child in root:
            if child.tag == 'loggedOut':
                self.loggedIn = False
            elif child.tag == 'error':
                print('Error:', child.attrib['message'])

        return not self.loggedIn

    def arena(self, teamid = 0):
        p = {'teamid': teamid}
        data = self.network.get('http://bbapi.buzzerbeater.com/arena.aspx', p)

        root = xml.fromstring(data)
        arena = root.find('arena')
        name = arena.find('name')

        arena_name = name.text
        arena_seats, arena_expansion = {}, {}

        seats = arena.find('seats')
        for seat in seats:
            arena_seats[seat.tag] = (int(seat.text),
                                     {'price': int(seat.attrib['price']),
                                      'nextPrice': int(seat.attrib['nextPrice'])})

        seats = arena.find('expansion')
        if seats is not None:
            arena_expansion['daysLeft'] = int(seats.attrib['daysLeft'])
            for seat in seats:
                arena_expansion[seat.tag] = int(seat.text)

        return arena_name, arena_seats, arena_expansion

    def countries_by_id(self):
        data = self.network.get('http://bbapi.buzzerbeater.com/countries.aspx')

        root = xml.fromstring(data)
        countries = root.find('countries')
        results = ['None'] # countries start from 1, 'None' fills the 0th place

        for country in countries:
            results.append({country.text: {'divisions': int(country.attrib['divisions']),
                                           'firstSeason': int(country.attrib['firstSeason']),
                                           'users': int(country.attrib['users'])}})
        return results

    def countries_by_name(self):
        data = self.network.get('http://bbapi.buzzerbeater.com/countries.aspx')

        # parse data
        root = xml.fromstring(data)
        countries = root.find('countries')
        results = {}

        for country in countries:
            results[country.text] = {'id': int(country.attrib['id']),
                                     'divisions': int(country.attrib['divisions']),
                                     'firstSeason': int(country.attrib['firstSeason']),
                                     'users': int(country.attrib['users'])}
        return results

    def economy(self):
        data = self.network.get('http://bbapi.buzzerbeater.com/economy.aspx')

        root = xml.fromstring(data)
        economy = root.find('economy')
        lastWeek = economy.find('lastWeek')
        thisWeek = economy.find('thisWeek')

        last, this = {}, {}
        for week in lastWeek:
            last[week.tag] = int(week.text)
        for week in thisWeek:
            this[week.tag] = int(week.text)
        return this, last

    def leagues(self, countryid, level):
        p = {'countryid': countryid, 'level': level}
        data = self.network.get('http://bbapi.buzzerbeater.com/leagues.aspx', p)

        root = xml.fromstring(data)
        division = root.find('division')

        # incorrect parameters
        if division is None:
            return {}

        leagues = {}
        for league in division:
            leagues[league.attrib['id']] = league.text
        return leagues

    def schedule(self, teamid = 0, season = 0):
        p = {'teamid': teamid, 'season': season}
        data = self.network.get('http://bbapi.buzzerbeater.com/schedule.aspx', p)

        root = xml.fromstring(data)
        schedule = root.find('schedule')
        for match in schedule:
            print(match.attrib['id'])
            print(match.attrib['type'])


    def standings(self, leagueid = 0, season = 0):
        p = {'leagueid': leagueid, 'season': season}
        data = self.network.get('http://bbapi.buzzerbeater.com/standings.aspx', p)

        root = xml.fromstring(data)
        standings = root.find('standings')
        regularSeason = standings.find('regularSeason')
        conference = regularSeason.find('conference')
        teams = []

        for team in conference:
            team_attr = {'id': team.attrib['id']}
            for attr in team:
                team_attr[attr.tag] = attr.text
            teams.append(team_attr)
        return teams

    def team_info(self, teamid = 0):
        p = {'teamid': teamid}
        data = self.network.get('http://bbapi.buzzerbeater.com/teamInfo.aspx', p)

        root = xml.fromstring(data)
        team = root.find('team')
        result = {}
        
        for attr in team:
            result[attr.tag] = (attr.text, attr.attrib)
        return result


